package uf.audit.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import uf.audit.db.*;
import uf.audit.util.AesUtil;
import uf.audit.util.Consts;
import uf.audit.util.Utils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 公共服务控制器类(放在这里的方法会被继承的Controller自动加入route，便于随时使用)
 *
 * @author sunny
 */
public class PubController extends UFBaseController {

    @SuppressWarnings("unchecked")
    public void getuserinfo() {
        String name = (String) getSessionAttr(Consts.SESSION_USERNAME_STR);
        String bh = Utils.getLogin(this);
        List<Integer> auths = (List<Integer>) getSessionAttr(Consts.SESSION_USERAUTH_STR);
        if (name == null || bh == null || auths == null) {
            name = "您未登录";
            bh = name;
            auths = new ArrayList<Integer>();
        }
        Properties p = new Properties();
        p.put("realname", name);
        p.put("userbh", bh);
        p.put("auths", auths);
        renderJson(p);
    }

    public void postpersondata() {
        JSONObject obj = JSONObject.parseObject(getPostData());
        if (User.dao.update(obj)) {
            //更新数据库中的用户数据后，需要更新session中的数据(如果是自己的话)
            String u = Utils.getLogin(this);
            if (u.equals(obj.get("userbh"))) {
                setSessionAttr(Consts.SESSION_USERNAME_STR, obj.get("realname"));//用户名
            }
            renderSuccess();
        } else {
            renderError();
        }
    }

    // 序列
    public void getseqlist() {
        renderJson(WorkSeq.dao.getSequences());
    }

    // 分类
    public void getcatelist() {
        renderJson(Category.dao.getcategories());
    }

    // 职级
    public void getlevellist() {
        renderJson(WorkLevel.dao.getlevels());
    }

    // 机构
    public void getorganizes() {
        renderJson(Organize.dao.getorganizes());
    }

    // 人员
    public void getpersonlist() {
        String dep = getPara("orgbh", null);
        renderJson(User.dao.getusers(dep));
    }

    /**
     * 个人信息
     */
    public void myinfo() {
        render("myinfo.html");
    }

    public void getmyself() {
        String userbh = Utils.getLogin(this);
        User user = User.dao.getuser(userbh);
        user.remove("password"); // 去除密码信息
        renderJson(user);
    }

    public void setpass() {
        String jsonStr = getPostData();
        JSONObject obj = JSON.parseObject(jsonStr);
        String userbh = obj.getString("userbh");
        String passwd = obj.getString("passwd");
        if (User.dao.setpass(userbh, passwd))
            renderSuccess();
        else
            renderError();
    }

    public void renderSuccess(String info) {
        renderJson("{\"status\":\"ok\", \"info\":\"" + info + "\"}");
    }

    /*
     * 登录
     */
    public void login() {
        HttpServletRequest request = getRequest();
        String method = request.getMethod().toUpperCase();
        if (method.equals("GET")) {
            if (Utils.isLogin(this)) { // 如果已经登录
                redirect("/index");
            } else { // 未登录
                render("login.html");
            }
        } else {
            String jsonStr = getPostData();
            JSONObject obj = JSON.parseObject(jsonStr);
            String email = obj.getString("email");
            String pass = obj.getString("password");
            String jym = obj.getString("jym");
            String kaptchaValue = (String) getSession(true)
                    .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
            System.out.println("kaptchaValue=>" + kaptchaValue);
           /* if (!kaptchaValue.equals(jym)) {
                renderError("登录失败，请确认登录信息是否正确");
                return;
            }*/
            User user = User.dao.checkUser(email, pass);
            if (user != null) {
                String userbh = user.getStr("userbh");
                Utils.setLogin(this, userbh);
                List<Integer> auths = Authentic.dao.getuserauth(userbh);
                String realname = user.getStr("realname");
                String username = user.getStr("username");
                if("audittest".equals(username)){
                    realname = "audittest";
                }
                if (realname == null) {
                    realname = "未命名";
                }
                setSessionAttr("username", username);
                setSessionAttr(Consts.SESSION_USERNAME_STR, realname);
                setSessionAttr(Consts.SESSION_USERAUTH_STR, auths);
                // ---
                setSessionAttr(Consts.AUTH_ADMIN_STR, false);
                setSessionAttr(Consts.AUTH_MARKING_STR, false);
                for (Integer auth : auths) {
                    if (auth == Consts.AUTH_ADMIN)
                        setSessionAttr(Consts.AUTH_ADMIN_STR, true);
                    if (auth == Consts.AUTH_MARKING)
                        setSessionAttr(Consts.AUTH_MARKING_STR, true);
                }
                renderSuccess();
            } else {
                renderError("登录失败，请确认登录信息是否正确");
            }
        }

    }

    /*
     * 注销
     */
    public void logout() {
        Jedis jedis = new Jedis("localhost");
        jedis.del(Utils.getLogin(this));
        Utils.cleanLogin(this);
        redirect("/login"); // 跳转到登录页面
    }

    // 当前时间
    public void getnowtime() {
        renderJson(Utils.getDateTime());
    }

    private static String jsContentCache = null;

    // 获取配置js
    public void js4pz() {
        String jsContent = "var __w = window;";
        if (enableAES()) {
            // iterationCount=1000
            // keySize=128
            // salt=e9f5dd179ca0c8e7d5bd0a3aa633629a
            // iv=ebf56d08aa6c9f13ccccc010c3e184b9
            // passphrase=123456
/*
follower code compress with http://www.sojson.com/yasuojs.html
(function() {
	var i = 7.94;
	i = ~~i;
	var j = 7.34;
	j = ~~j;
	__w = window;
	__w.ep = {
		'k': 'e9f5dd179ca0c8e7d5bd0a3aa633629a' //salt
	};
	__w.ep.l = 'ebf56d08aa6c9f13ccccc010c3e184b9'; // iv
	var myArray = new Array();
	myArray.push('D5417070-8B85-44AD-BC05-6C8D63175BD3'); // passphrase
	myArray.push(1000); // iterationCount
	myArray.push(128); // keySize
	myArray.push('a');
	__w.ep.m = myArray[0];
	myArray.push('e');
	myArray.push('ep');
	__w.ep.c = myArray[1];
	myArray.push('c');
	myArray.push('d');
	var random = myArray[~~ (Math.random() * myArray.length)];
	__w.ep.d = myArray[2];
	//	console.log(random);
})();

======>

=(function(){var i=7.94;i=~~i;var j=7.34;j=~~j;__w=window;__w.ep={'k':'e9f5dd179ca0c8e7d5bd0a3aa633629a'};__w.ep.l='ebf56d08aa6c9f13ccccc010c3e184b9';var myArray=new Array();myArray.push('D5417070-8B85-44AD-BC05-6C8D63175BD3');myArray.push(1000);myArray.push(128);myArray.push('a');__w.ep.m=myArray[0];myArray.push('e');myArray.push('ep');__w.ep.c=myArray[1];myArray.push('c');myArray.push('d');var random=myArray[~~(Math.random()*myArray.length)];__w.ep.d=myArray[2]})();

 */

            String formatStr = "(function(){var i=7.94;i=~~i;var j=7.34;j=~~j;__w=window;__w.ep={'k':'%s'};__w.ep.l='%s';var myArray=new Array();myArray.push('%s');myArray.push(%s);myArray.push(%s);myArray.push('a');__w.ep.m=myArray[0];myArray.push('e');myArray.push('ep');__w.ep.c=myArray[1];myArray.push('c');myArray.push('d');var random=myArray[~~(Math.random()*myArray.length)];__w.ep.d=myArray[2]})();";
            if (jsContentCache == null) {
                String salt = prop.getProperty("salt");
                String iv = prop.getProperty("iv");
                String passphrase = AesUtil.PASSPHRASE;
                String iterationCount = prop.getProperty("iterationCount");
                String keySize = prop.getProperty("keySize");
                jsContentCache = String.format(formatStr, salt, iv, passphrase, iterationCount, keySize);
            }
            jsContent = jsContentCache;
        }
        renderText(jsContent, "text/javascript");
    }

    // 文档下载页面
    public void downloaddoc() {
        render("docs.html");
    }

    // 获取所有文档
    public void getdownloaddocs() {
        renderJson(Docs.dao.getdocs());
    }
}
